package com.atguigu.tingshu.search.service.impl;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.CategoryFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.PinYinUtils;
import com.atguigu.tingshu.model.album.AlbumAttributeValue;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.search.dao.AlbumInfoIndexDao;
import com.atguigu.tingshu.search.dao.SuggestIndexDao;
import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author sun
 */
@Slf4j
@Service
public class ItemServiceImpl implements ItemService {

    @Resource
    private AlbumInfoIndexDao albumInfoIndexDao;

    @Resource
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Resource
    private UserInfoFeignClient userInfoFeignClient;

    @Resource
    private CategoryFeignClient categoryFeignClient;

    @Resource
    private SuggestIndexDao suggestIndexDao;

    /**
     * 添加专辑到ES
     *
     * @param albumId 专辑id
     */
    @Override
    public void addAlbumSearch(Long albumId) {
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
        // 查询专辑的详细数据
        AlbumInfo albumInfo = albumInfoFeignClient.getAlbumInfo(albumId);
        // TODO albumInfo.getId() 缓存的id可能为空
        if (albumInfo == null || albumInfo.getId() == null) {
            log.error("{}专辑不存在", albumId);
            return;
        }
        albumInfoIndex.setId(albumId);
        albumInfoIndex.setAlbumTitle(albumInfo.getAlbumTitle());
        albumInfoIndex.setAlbumIntro(albumInfo.getAlbumIntro());
        // 专辑作者
        Long userId = albumInfo.getUserId();
        String name = userInfoFeignClient.getUserNameById(userId);
        if (name == null) {
            log.error("{}用户不存在", userId);
            return;
        }
        albumInfoIndex.setAnnouncerName(name);
        albumInfoIndex.setCoverUrl(albumInfo.getCoverUrl());
        albumInfoIndex.setIncludeTrackCount(albumInfo.getIncludeTrackCount());
        albumInfoIndex.setIsFinished(String.valueOf(albumInfo.getIsFinished()));
        albumInfoIndex.setPayType(albumInfo.getPayType());
        albumInfoIndex.setCreateTime(new Date());

        // 设置分类id
        BaseCategoryView categoryView = categoryFeignClient.getCategoryView(albumInfo.getCategory3Id());
        if (categoryView == null) {
            log.error("{}分类不存在", albumInfo.getCategory3Id());
            return;
        }
        albumInfoIndex.setCategory1Id(categoryView.getCategory1Id());
        albumInfoIndex.setCategory2Id(categoryView.getCategory2Id());
        albumInfoIndex.setCategory3Id(albumInfo.getCategory3Id());

        // 查询专辑的统计数据
        Map<String, Integer> albumStats = albumInfoFeignClient.getAlbumStats(albumId);
        if (albumStats == null) {
            log.error("{}专辑统计不存在", albumId);
            return;
        }

        albumInfoIndex.setBuyStatNum(albumStats.get(SystemConstant.ALBUM_STAT_BROWSE));
        albumInfoIndex.setCommentStatNum(albumStats.get(SystemConstant.ALBUM_STAT_COMMENT));
        albumInfoIndex.setPlayStatNum(albumStats.get(SystemConstant.ALBUM_STAT_PLAY));
        albumInfoIndex.setSubscribeStatNum(albumStats.get(SystemConstant.ALBUM_STAT_SUBSCRIBE));
        // 热度评分 = 播放量 * 0.1 + 订阅量 * 0.2 + 评论量 * 0.3 + 购买量 * 0.5
        albumInfoIndex.setHotScore(
                (albumInfoIndex.getPlayStatNum() * 0.1) +
                        (albumInfoIndex.getSubscribeStatNum() * 0.2) +
                        (albumInfoIndex.getCommentStatNum() * 0.3) +
                        (albumInfoIndex.getBuyStatNum() * 0.5)
        );
        // 查询专辑的标签属性数据
        List<AlbumAttributeValue> albumAttributes = albumInfoFeignClient.getAlbumAttributes(albumId);
        if (albumAttributes == null) {
            log.error("{}专辑标签属性不存在", albumId);
            return;
        }

        List<AttributeValueIndex> attributeValueIndexes = albumAttributes.stream().map(albumAttribute ->
                AttributeValueIndex.builder()
                        .attributeId(albumAttribute.getAttributeId())
                        .valueId(albumAttribute.getValueId())
                        .build()
        ).toList();
        albumInfoIndex.setAttributeValueIndexList(attributeValueIndexes);

        albumInfoIndexDao.save(albumInfoIndex);

        // 提示词初始化
        suggestInit(albumInfoIndex);
    }

    /**
     * 初始化提示词
     *
     * @param albumInfoIndex 专辑索引数据
     */
    private void suggestInit(AlbumInfoIndex albumInfoIndex) {
        Long id = albumInfoIndex.getId();

        // 专辑标题
        String albumTitle = albumInfoIndex.getAlbumTitle();
        saveSuggest(id, albumTitle, albumTitle);
        // 作者名字
        String announcerName = albumInfoIndex.getAnnouncerName();
        saveSuggest(id, announcerName,albumTitle);
        // 专辑简介
        String albumIntro = albumInfoIndex.getAlbumIntro();
        saveSuggest(id, albumIntro, albumTitle);

    }

    /**
     * 保存提示词
     * @param id 专辑id
     * @param content 提示关键字
     * @param albumTitle 提示内容-->专辑标题
     */
    private void saveSuggest(Long id, String content, String albumTitle) {
        suggestIndexDao.save(SuggestIndex.builder()
                .id(id + content)
                .title(albumTitle)
                .keyword(new Completion(new String[]{content}))
                .keywordPinyin(new Completion(new String[]{PinYinUtils.toHanyuPinyin(content)}))
                .keywordSequence(new Completion(new String[]{PinYinUtils.getFirstLetter(content)}))
                .build());
    }

    /**
     * 在ES中删除专辑
     *
     * @param userId 用户id
     */
    @Override
    public void removeAlbumSearch(Long userId) {
        albumInfoIndexDao.deleteById(userId);
    }
}
